package com.mybatis.jpa.statement.builder;

import com.mybatis.jpa.meta.MybatisColumnMeta;
import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;
import com.mybatis.jpa.statement.SqlAssistant;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 批处理插入
 * @author wanglei
 * @date 2020 -02-06 11:06:32
 */
public class BatchInsertBuilder extends BaseInsertBuilder{

	@Override
	public String buildSQL(PersistentMeta persistentMeta, Method method) {
		StringBuilder values = new StringBuilder();

		for (MybatisColumnMeta columnMeta : persistentMeta.getColumnMetaMap().values()) {

			if (values.length() > 0) {
				values.append(",");
			}
			if(columnMeta.isVersion())
			{
				values.append(0);
			}
			else{
				values.append(SqlAssistant.resolveSqlParameter(columnMeta, "rowData"));
			}

		}
		return "<script>" + " INSERT INTO " + persistentMeta.getFlagTableName() + " (" + persistentMeta.getColumnNames()
        + " ) " + " VALUES " + "<foreach item='rowData' index='rowIndex' collection='list' separator=','>"
        + "( " + values + " )" + "</foreach></script>";
	}

	@Override
	public void parseStatement(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method) {
		// 方法名
		adapter.setMethodName(method.getName());
		// 参数类型
		adapter.setParameterTypeClass(java.util.Map.class);
		// sqlScript
		adapter.setSqlScript(buildSQL(persistentMeta, method));
		super.setKeyGenerator(adapter,persistentMeta,method);
		adapter.parseStatement();

	}

}
